<?php

namespace app\home\controller;

use app\home\controller;
use app\home\model\PatrolDeviceItemTaskM;
use app\home\model\PatrolDeviceM;
use app\home\model\PatrolTaskM;
use myResponse\Res;
use think\Db;
use think\Request;
use app\facade;

//巡检任务
class PatrolTask extends Base
{

    function getTime()
    {
        $min=TIME_SPAN ;
//        $t[0] = date("Y-m-d H:i:s", strtotime("-".$min." minutes"));
        $t = date("Y-m-d H:i:s", strtotime("+".$min." minutes"));
        return $t;
    }
    //下次生成时间<比较时间 保留当前项去生成
    function compareTime($time)
    {
        $min=TIME_SPAN ;
        $t= date("Y-m-d H:i:s", strtotime("+".$min." minutes"));
        if( $time<=$t)
            return false;
        else
            return true;
    }

// 算时间插表
    function durationTime($d, $u, $todotime)
    {
        return date("Y-m-d H:i:s", strtotime($todotime) + $d * $u * 3600);
    }



    function task()
    {
        //todo // patrol_device_item_task
//        patrol_task 任务生成 及历史
        // patrol_device nearTime 最近的
        // line device onlyone

//        $minute=floor((strtotime($enddate)-strtotime($startdate))%86400/60);
        //1. 由nearTime查询相关设备下的检查项
        //2. nearTime 触发设备检查项patrol_device_item_task nextTime比较
        //3. patrol_device_item_task nexttime 项下次产生任务时间
        //4. line   新增,删除  patrol_device_item_task LineId 的记录全部删除
        //5. device  重置点检line  patrol_device_item_task LineId 的记录全部删除
        //6. item   重置line-device patrol_device_item_task LineId 的记录全部删除

        $wheretime = $this->getTime();
        $list = Db::view('patrol_device b', '*')
            ->view('patrol_line a', 'LineName, ModeId', 'a.LineID=b.LineID', 'left')
            ->view('sb c', 'sbdh, sbmc, checkStandardId', 'b.sbid=c.sbid')
            ->view('check_standard d', 'StandardName', 'c.checkStandardId=d.StandardId')
            ->view('check_standard_item e', 'ItemId, CheckPosition,CheckContent,Param,CheckJob,CycleTypeId', 'c.checkStandardId=e.StandardId')
            ->view('check_cycle_type f', 'CycleType,CycleHour', 'e.CycleTypeId=f.CycleTypeId', 'left')
            ->view('check_cycle_model_time g', 'duration, unit', 'a.ModeId=g.ModeId and f.CycleTypeId=g.CycleTypeId', 'left')
            ->view('check_cycle_model h', 'ModeName', 'g.ModeId=h.ModeId', 'left')
            ->view('patrol_device_item_task t', 'id, nextTime', 'b.LineID=t.LineID and b.sbid=t.sbid and e.ItemId=t.ItemId ', 'left')
            ->view('sys_user u', 'UserName as CreateName', 'd.Creator=u.UserId', 'left')
            ->order('b.LineID asc, b.SbSort asc, b.CreateTime asc')
//            ->where($map)
            ->whereTime('nearTime', '<', $wheretime)
            ->select();

        //df($list);
        //patrol_task 任务生成 及历史
        //patrol_device_item_task

        $itemTask = []; // 待生成任务数组
        $itemNearTime = []; // 所有以设备分组在检项下次检查时间
//        $itemSearch = [];
        foreach ($list as $k => $v) {
            //优化项
            $key=$v['PatrolDeviceID'].','.$v['LineID'].','.$v['sbid'];
            $stime = $v['nextTime'];
            // 判断当前时间与项的下次时间
            if($this->compareTime($stime)){
                $itemNearTime[$key][]= $v['nextTime']; //存时间
//                echo $k.'没到时间!'.$v['LineID'].'-'.$v['sbid'].'-'.$v['ItemId'].'<br/>';
                continue;
            }
            // 要产生的item
//            echo $k.'生成---'.$v['PatrolDeviceID'].','.$v['LineID'].'-'.$v['sbid'].'-'.$v['ItemId'].'<br/>';

            //patrol_device_item_task 没有记录 以patrol_device表 standardNextTime 为基准 (更改设置项或新生成的巡检任务)
            if(!$stime){
                $stime=date('Y-m-d '). $v['standardNextTime'];
// 当前时间超过标准 推迟到下一天标准时间
//                if($stime<date('Y-m-d H:i:s'))
//                    $stime = date("Y-m-d ",strtotime("+1 day")).$v['standardNextTime'];
            }

            $etime = $this->durationTime($v['duration'], $v['unit'], $stime);
            $nextTime = $this->durationTime($v['CycleHour'], 1, $stime);
//            dump($stime);dump($etime);dump($nextTime);echo '------<br/>';
            $vv = $v;
            $vv['nextTime'] = $nextTime;
            $vv['stime'] = $stime;
            $vv['etime'] = $etime;
            $vv['TaskNo'] = $key.','.$v['ItemId'];
            $itemTask[$k]=$vv;
            $itemNearTime[$key][]= $vv['nextTime'];//存时间
        }

        //        df($itemNearTime);
//        dd($itemTask);
        //所有设备在检项比较时间取最小值
        $nearTime= [];
        $i=0;
        foreach ($itemNearTime as $key=>$t){
            $k=explode(',',$key);
            $cp =$t[0];
            foreach($t as $st){
                $cp = $cp>$st?$st:$cp;
            }
            $nearTime[$i]['PatrolDeviceID']=$k[0];
            $nearTime[$i]['nearTime']=$cp;
            $i++;

        }


//        df($nearTime); //最后生成的patrol_device nearTime插表数组

        //插表
        $pt = new PatrolTaskM();
        $pt->saveMore($itemTask);   // 产生任务
        $m = new PatrolDeviceItemTaskM();
        $m->allowField(true)->saveAll($itemTask); // 任务项记录下次时间
        $pd = new PatrolDeviceM();
        $pd->allowField(true)->saveAll($nearTime);  //更新下次时间
        Res::suc('调用接口成功!');
        die;

        // 假设没有id  去表中查
/*        foreach($itemSearch as $k=>$v){
            $key = explode(',',$k);
            $we['LineID'] = $key[0];
            $we['sbid'] = $key[1];
            //线-设备下所有巡检项
            $rec = $m->where($we)->select();
            //存在的[item] = id
            $itemHistory=[];
            foreach ($rec as $w){
                $itemHistory[$w['ItemId']] =$w['id'];
            }
            dd($itemHistory);
//            dd($rec);
//            dd($v);
            //比较 line - device 中的 item 赋值 id
            if(count($v)){
                $itemNewData=[];
                foreach ($v as $sk=>$vv){
                    $itemNewData[$sk]=$vv;
                    $id =$vv['ItemId'];
                    echo '<br/>---id---:';
                    dd($id);
                    if(isset($itemHistory[$id])) {
                        $itemNewData[$sk]['id']=$itemHistory[$id];
                        unset($itemHistory[$vv['ItemId']]);
                    }
                }
//                dd(array_values($itemHistory));
//                die;
                $m->delMore(array_values($itemHistory)); //删除过期的
                $m->saveMore($itemNewData); //无id插入新的, 有id修改

            }
            dd($itemHistory);
            dd($itemNewData);
//            dd($val);

        }*/

    }

    function getList()
    {
        $m = new PatrolTaskM;
        $z = $m->listP();
        Res::suc('ok', $z);
    }

    //删除
    function delOne()
    {
        $m = new PatrolTaskM;
        $r = Db::table('sbbj')->where('sbid = ' . input('sbid'))->delete();
        $this->ret($m->delOne(), 2);
    }

    function ret($z, $tp)
    {
        $ret = ['添加', '修改', '删除'];
        if ($z)
            Res::suc($ret[$tp] . '成功！');
        else
            Res::errs($ret[$tp] . '失败！');
    }
}